<template>
  <div id="submit">
    <!-- 信息填写区域 -->
    <van-cell> 收货地址 </van-cell>

    <van-button
      v-if="!addrList.length"
      size="large"
      type="danger"
      icon="plus"
      @click="show = !show"
      >添加地址</van-button
    >
    <van-panel
      v-else
      :title="chosenAddr.name"
      :status="chosenAddr.tel"
      :desc="chosenAddr.address"
      @click="show = !show"
    ></van-panel>
    <!-- 选择地址路由导航 -->
    <van-action-sheet title="选择地址" v-model="show" @select="onSelect">
      <van-address-list
        v-model="chosenAddressId"
        :list="addrList"
        @add="onNewAddr"
        @edit="onEdit"
      />
    </van-action-sheet>

    <van-cell> 订单 ({{ totalCount }}) </van-cell>
    <!-- 商品信息卡 -->
    <van-cell-group v-for="(item, index) in orderList" :key="index">
      <van-card
        class="card"
        :title="item.name"
        :desc="item.info"
        :num="item.count"
        :thumb="'data:image;base64,' + item.images[0]"
        :price="item.current_price"
      />
    </van-cell-group>
    <!-- 下单按钮 -->
    <div style="height:50px;" />
    <van-submit-bar
      :price="totalPrice"
      button-text="下单"
      @submit="onSubmit"
      :disabled="chosenAddr == null"
    />
  </div>
</template>

<script>
import { axios, API_URL } from "../../api"
import {
  SubmitBar,
  Cell,
  CellGroup,
  Toast,
  ActionSheet,
  AddressList,
  Button,
  Panel,
  Card
} from "vant"

export default {
  components: {
    [SubmitBar.name]: SubmitBar,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [ActionSheet.name]: ActionSheet,
    [AddressList.name]: AddressList,
    [Button.name]: Button,
    [Panel.name]: Panel,
    [Card.name]: Card
  },
  data() {
    return {
      onSelect: 1,
      chosenAddressId: 0,
      list: [],
      orderList: [],
      show: false,
      addrList: []
    }
  },
  computed: {
    /* 计算所选商品总价 */
    totalPrice() {
      return (
        this.orderList.reduce(
          (total, item) => total + item.current_price * item.count,
          0
        ) * 100
      )
    },
    /* 计算所选商品总数 */
    totalCount() {
      return this.orderList.reduce((total, item) => total + item.count, 0)
    },
    /* 返回所选地址实例 */
    chosenAddr() {
      return this.addrList[this.chosenAddressId]
    }
  },
  methods: {
    onEdit(item, index) {
      this.$router.push({
        name: "addrEdit",
        query: {
          editType: "editOldAddr",
          receiver: item.name,
          phone: item.tel,
          address: item.address,
          address_id: item.address_id
        }
      })
    },
    onNewAddr() {
      this.$router.push({
        name: "addrEdit",
        query: {
          editType: "addNewAddr"
        }
      })
    },
    selectedAddr() {
      this.addrList.forEach(item => {
        if (item.id == this.chosenAddressId) {
          return item
        }
      })
    },
    onAddrClick() {
      this.$router.push({ name: "addrList" })
    },
    onSubmit() {
      let address_id = 0
      this.addrList.forEach(item => {
        if (item.id == this.chosenAddressId) {
          address_id = item.address_id
        }
      })
      axios
        .post(
          API_URL + "order/create",
          {
            address_id: address_id
          },
          {
            headers: {
              Authorization: this.$store.state.customer_token
            }
          }
        )
        .then(() => {
          Toast.success("订单提交成功")
          this.$router.replace({ name: "userCenter" })
        })
        .catch(err => {
          if (err.response.data.message == "Invalid address id")
            Toast.fail("请选择正确的地址")
          else console.error(err)
        })
    }
  },

  mounted: function() {
    /* 预载已有订单信息：地址列表信息，订单商品信息 */
    axios
      .get(API_URL + "address", {
        headers: {
          authorization: this.$store.state.customer_token
        }
      })
      .then(response => {
        response.data.addrs.forEach((item, index) => {
          this.addrList.push({
            id: index,
            name: item.receiver,
            tel: item.phone,
            address: item.address,
            address_id: item.id
          })
        })
      })
      .catch(err => {
        console.error(err)
      })
    // 获取商品的item_id
    axios
      .get(API_URL + "cart", {
        headers: {
          Authorization: this.$store.state.customer_token
        }
      })
      .then(response => {
        let items = response.data.items
        items.forEach((item, index) => {
          let tmpItem = {}
          // 通过item_id获取商品信息
          tmpItem.id = index
          axios
            .get(API_URL + "items/" + item.item_id, {})
            .then(response => {
              if (item.selected) {
                tmpItem.item_id = item.item_id
                tmpItem.selected = item.selected
                tmpItem.count = item.count
                tmpItem.name = response.data.name
                tmpItem.current_price = response.data.current_price
                tmpItem.original_price = response.data.original_price
                tmpItem.in_stock = response.data.in_stock
                tmpItem.info = response.data.info
                tmpItem.sales = response.data.sales
                tmpItem.shop_id = response.data.shop_id
                tmpItem.images = response.data.images
                this.orderList.push(tmpItem)
              }
            })
            .catch(err => {
              console.error(err)
            })
        })
      })
      .catch(err => {
        console.error(err)
      })
  }
}
</script>
